// 云函数入口文件
const cloud = require('wx-server-sdk')
const TcbRouter = require('tcb-router')
const rp = require('request-promise')
const BASE_URL = 'http://musicapi.xiecheng.live'
cloud.init()

// 云函数入口函数
exports.main = async (event, context) => {
  const app = new TcbRouter({ event })
  //获取展示列表
  app.router('playlist', async(ctx, next) => {
    const result = await cloud.database().collection('playlist')
      .skip(event.start)
      .limit(event.count)
      .orderBy('createTime', 'desc')
      .get()
      
      ctx.body = result
  })
  //获取音乐列表
  app.router('musiclist', async(ctx, next) => {
    const result = await rp(BASE_URL + '/playlist/detail?id=' + parseInt(event.playlistId))        
    ctx.body = JSON.parse(result)
  })
  //获取音乐
  app.router('musicUrl', async(ctx,next) => {
    const result = await rp(BASE_URL + `/song/url?id=${event.musicId}`)
    ctx.body = JSON.parse(result) 
  })

  //获取歌词
  app.router('lyric', async(ctx, next) => {
    const result = await rp(BASE_URL + `/lyric?id=${event.musicId}`)
    ctx.body = JSON.parse(result) 
  })

  //获取单首音乐详情
  app.router('musicdetail', async (ctx) => {
    const musicId = event.musicId
    let result = await rp(BASE_URL+ `/song/detail?ids=${musicId}`)
    result = JSON.parse(result)
    ctx.body = result
  })

  //获取音乐详情数组
  app.router('musicDetail', async(ctx) => {
    let  list =  event.musicIdList
    list.map( item => parseInt(item))
    let musiclist = []
    for(let i = 0; i < list.length; i++) {
      let result = await rp(BASE_URL + `/song/detail?ids=${list[i]}`)
      result = JSON.parse(result)
      musiclist.push(result.songs[0])
    }
    ctx.body = musiclist
  })
  return app.serve()
}